package org.txazo.blog.commons.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.txazo.blog.util.log.LoggerManager;

/**
 * Spring JdbcTemplate AOP拦截
 * 
 * @author Tu XiaoZhou
 * @since 2013-08-14
 * 
 */
@Aspect
@Component
public class SpringJdbcLogAspect {

	private static final String methodNames = "update^queryForObject^queryForList";

	@Pointcut("execution(* org.springframework.jdbc.core.JdbcTemplate.*(..))")
	private void pointcut() {
	}

	@Around("pointcut()")
	public Object around(ProceedingJoinPoint proceedingJoinPoint)
			throws Throwable {
		String methodName = proceedingJoinPoint.getSignature().getName();
		Object[] args = proceedingJoinPoint.getArgs();

		if (methodNames.contains(methodName) && args[0] instanceof String) {
			String sql = args[0].toString();

			int index = 1;
			while (index < args.length
					&& (args[index] instanceof Class
							|| args[index] instanceof RowMapper || args[index] instanceof PreparedStatementSetter)) {
				index++;
			}

			if (args[index] != null) {
				Object[] params = (Object[]) args[index];
				for (Object param : params) {
					sql = sql.replaceFirst("\\?", param.toString());
				}
			}

			LoggerManager.getJdbcLogger().info("[sql]: " + sql);
		}

		return proceedingJoinPoint.proceed();
	}

}
